package com.thornbird.vehiclerecycling.service.impl;

import com.thornbird.vehiclerecycling.entity.Config;
import com.thornbird.vehiclerecycling.model.record.ConfigRecord;
import com.thornbird.vehiclerecycling.repository.ConfigRepository;
import com.thornbird.vehiclerecycling.service.ConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(rollbackFor = Exception.class)
public class ConfigServiceImpl implements ConfigService {

    private final ConfigRepository configRepository;

    @Autowired
    public ConfigServiceImpl(ConfigRepository configRepository) {
        this.configRepository = configRepository;
    }

    @Override
    public ConfigRecord findConfig() {
        Config config = configRepository.findFirstByOrderByIdAsc();
        if (config == null) {
            config = createConfig();
            configRepository.save(config);
        }
        ConfigRecord configRecord = new ConfigRecord();
        configRecord.parseEntity(config);
        return configRecord;
    }

    @Override
    public ConfigRecord saveConfig(Config config) {
        if (config.getId() == null || config.getId() <= 0) {
            Config currentConfig = configRepository.findFirstByOrderByIdAsc();
            if (currentConfig != null) {
                config.setId(currentConfig.getId());
            } else {
                config.setId(null);
            }
        }
        configRepository.save(config);
        return findConfig();
    }

    private Config createConfig() {
        Config config = new Config();
        config.setDefaultRemark("本表一式六联：一联车主留存；二联交当地公安交通管理部门备查；三联回收企业留存；"
                .concat("四联交当地商务主管部门备查；五联用于申领补贴资金；六联交当地交通运输管理部门备查"));
        config.setVehicleTypes("大型汽车,小型汽车,专用汽车,特种车,有轨电车,无轨电车,电瓶车,三轮摩托车,二轮摩托车,轻便摩托车,"
                .concat("四轮农用运输车,三轮农用运输车,大型方向盘式拖拉机,小型方向盘式拖拉机,手扶拖拉机,轮式自行专用机械,")
                .concat("全挂车,半挂车"));
        config.setVehicleNatures("非营运,营运,租赁,货运,危险化学品运输,教练车,警车,消防车,救护车");
        config.setPowerTypes("燃油,混合动力,纯电动");
        return config;
    }

}
